<template>
  <div class="content-section fans-section">
    <div class="section-header">
      <h2 class="section-title">我的粉丝 ({{ dataList.length }})</h2>
    </div>
    <div class="user-list" ref="userList" @scroll="handleScroll">
      <transition-group name="user-item" tag="div">
        <div v-for="fan in dataList" :key="fan.id" class="user-item">
          <img :src="fan.avatar" :alt="fan.username" class="user-avatar" />
          <div class="user-info">
            <h4 class="user-nickname">{{ fan.username }}</h4>
            <p class="user-follow-time">关注时间: {{ fan.followTime }}</p>
          </div>
          <button
            :class="[
              'btn-follow',
              {
                loading: fan.isFollowLoading,
                'mutual-follow': fan.isMutualFollow,
                'follow-back': !fan.isMutualFollow,
              },
            ]"
            @click="handleFollowAction(fan)"
            :disabled="fan.isFollowLoading"
          >
            <span class="btn-text">
              {{ fan.isFollowLoading ? '处理中...' : fan.isMutualFollow ? '互相关注' : '回关' }}
            </span>
            <span class="btn-loading" v-if="fan.isFollowLoading">
              <span class="loading-spinner"></span>
            </span>
          </button>
        </div>
      </transition-group>
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <span class="loading-text">加载中...</span>
      </div>

      <!-- 到底提示 -->
      <div v-if="isLastPage && dataList.length > 10" class="end-tip">
        <span>已经到底了</span>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && dataList.length === 0" class="empty-state"> 暂无粉丝 </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { getFansListApi, followUserApi, unFollowUserApi } from '@/api/system/user';
  import { ref, onMounted } from 'vue';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  const userList = ref(null);

  const userInfo = ref<any>(null);

  const handleFollowAction = async (fan: any) => {
    if (!fan || fan.isFollowLoading) return;

    fan.isFollowLoading = true;

    try {
      if (fan.isMutualFollow) {
        await unFollowUserApi(fan.userId);
        fan.isMutualFollow = false;
        console.log(`✅ 取消关注用户: ${fan.username}`);
      } else {
        await followUserApi(fan.userId);
        fan.isMutualFollow = true;
        console.log(`✅ 成功回关用户: ${fan.username}`);
      }
    } catch (error) {
      console.error('❌ 操作失败:', error);
    } finally {
      fan.isFollowLoading = false;
    }
  };

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const loading = ref(false);
  const isLastPage = ref(false);
  const dataList = ref<any[]>([]);

  async function loadData(isRefresh = false) {
    if (!userInfo.value || loading.value || (isLastPage.value && !isRefresh)) return;

    loading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
      };

      const data: any = await getFansListApi(userInfo.value.userId, params);

      let list = data.records || [];

      if (isRefresh) {
        dataList.value = list;
      } else {
        dataList.value = [...dataList.value, ...list];
      }

      if (list.length < 10) {
        isLastPage.value = true;
      }

      if (!isLastPage.value) {
        pageNum.value++;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      loading.value = false;
    }
  }

  function resetPage() {
    pageNum.value = 1;
    isLastPage.value = false;
    dataList.value = [];
  }

  const handleScroll = () => {
    if (!userList.value) return;

    const { scrollTop, scrollHeight, clientHeight } = userList.value;

    // 当滚动到距离底部50px时触发加载
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      loadData();
    }
  };

  onMounted(() => {
    userInfo.value = userStore.info || {};
    resetPage();
    loadData(true);
  });
</script>

<style lang="less">
  .user-list {
    max-height: 500px;
    overflow-y: auto;
    padding-right: 8px;

    .user-item {
      display: flex;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid #f1f5f9;

      &:last-child {
        border-bottom: none;
      }

      .user-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        margin-right: 16px;
        object-fit: cover;
        border: 2px solid #e2e8f0;
      }

      .user-info {
        flex: 1;

        .user-nickname {
          margin: 0 0 4px;
          font-size: 16px;
          font-weight: 600;
          color: #1e293b;
        }

        .user-follow-time {
          margin: 0;
          font-size: 14px;
          color: #64748b;
        }
      }

      .btn-follow {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        color: white;
        border: none;
        border-radius: 20px;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        width: 120px;
        justify-content: center;

        &:hover {
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(0);
        }

        &:disabled {
          opacity: 0.7;
          cursor: not-allowed;
          transform: none;
        }

        .btn-text {
          transition: all 0.3s ease;
        }

        .btn-loading {
          display: flex;
          align-items: center;
          justify-content: center;

          .loading-spinner {
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top: 2px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
          }
        }

        &.loading {
          .btn-text {
            opacity: 0.8;
          }
        }

        // 互相关注状态 - 浅灰色
        &.mutual-follow {
          background: #9ca3af; // 浅灰色
        }

        // 回关状态 - 浅粉色
        &.follow-back {
          background: #f8b4c4; // 浅粉色
        }
      }
    }
  }

  // 过渡动画
  .user-item-enter-active {
    transition: all 0.6s ease-out;
  }

  .user-item-leave-active {
    transition: all 0.3s ease-in;
  }

  .user-item-enter-from {
    opacity: 0;
    transform: translateY(-20px) scale(0.9);
  }

  .user-item-leave-to {
    opacity: 0;
    transform: translateY(-20px) scale(0.8);
    height: 0;
    padding: 0;
    margin: 0;
  }

  .user-item-move {
    transition: transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  }

  // 加载动画
  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .user-list {
      .user-item {
        padding: 12px 0;

        .user-avatar {
          width: 45px;
          height: 45px;
          margin-right: 12px;
        }

        .user-info {
          .user-nickname {
            font-size: 15px;
          }

          .user-follow-time {
            font-size: 13px;
          }
        }

        .btn-follow {
          padding: 6px 12px;
          font-size: 13px;
          width: 100px;

          .btn-icon {
            font-size: 14px;
          }

          .btn-loading .loading-spinner {
            width: 14px;
            height: 14px;
          }
        }
      }
    }
  }
</style>
